/* eslint-disable react/display-name */
import React from 'react'
import { Image, View, AppState, DeviceEventEmitter } from 'react-native'
import PropTypes from 'prop-types'
import { createBottomTabNavigator, createAppContainer } from 'react-navigation'
import JPushModule from 'jpush-react-native'
import { IS_IOS } from 'src/utils/ScreenUtil'
import CMessagePage from '../pageC/message/message-page/index'
import CMinePage from '../pageC/mine/mine-page/index'
import CPositionPage from './position/position-page/index2'
import IMController from 'src/utils/IMController'
import { Bridge, tabBarIconStyle } from 'src/pageB/tabbar'
/* redux */
import { connect } from 'react-redux'
import {
  DO_REQUEST_MAIN_PAGE_C_ACTION,
  DO_REQUEST_MY_CENTER_NUMBERS_ACTION
} from './mine/mine-page/store/action'
import { DO_REQUEST_USERINFO_C_ACTION } from 'src/store/actions/userinfo'
import TouchableBounce from 'react-native/Libraries/Components/Touchable/TouchableBounce'
import { isString } from 'src/utils/JSTypeUtil'
import CHomePage from 'src/pageC/home/home-page'
import { initKeywordBlockObj } from 'src/utils/RegUtil'

export const C_POSITION_REFRESH = 'C_POSITION_REFRESH' // C端首页刷新监听KEY
const TabRouteConfigs = {
  CHomePage: {
    screen: CHomePage,
    navigationOptions: {
      tabBarLabel: '首页',
      tabBarIcon: ({ focused }) => (
        <Image
          style={tabBarIconStyle}
          source={
            focused
              ? require('../imgC/tab/home_selected.png')
              : require('../imgC/tab/home.png')
          }
        />
      )
    }
  },
  CPositionPage: {
    screen: CPositionPage,
    navigationOptions: ({ screenProps: { activeIndex } }) => {
      const refreshClick = activeIndex === 1
      return {
        tabBarLabel: '职位',
        tabBarIcon: ({ focused }) => (
          <Image
            style={tabBarIconStyle}
            source={
              focused
                ? require('../imgC/tab/position_selected.png')
                : require('../imgC/tab/position.png')
            }
          />
        ),
        tabBarOnPress: ({ defaultHandler }) => {
          if (refreshClick) {
            // 需要刷新
            DeviceEventEmitter.emit(C_POSITION_REFRESH)
          }
          defaultHandler()
        },
        tabBarButtonComponent: refreshClick ? TouchableBounce : null
      }
    }
  },
  CMessagePage: {
    screen: CMessagePage,
    navigationOptions: ({ screenProps }) => ({
      tabBarLabel: '消息',
      tabBarIcon: ({ focused }) => {
        return (
          <View style={{ position: 'relative' }}>
            {!!screenProps.bridge && <Bridge/>}
            <Image
              style={tabBarIconStyle}
              source={
                focused
                  ? require('../imgC/tab/message_selected.png')
                  : require('../imgC/tab/message.png')
              }
            />
          </View>
        )
      }
    })
  },
  CMinePage: {
    screen: CMinePage,
    navigationOptions: {
      tabBarLabel: '我的',
      tabBarIcon: ({ focused }) => (
        <Image
          style={tabBarIconStyle}
          source={
            focused
              ? require('../imgC/tab/mine_selected.png')
              : require('../imgC/tab/mine.png')
          }
        />
      ),
      tabBarOnPress: ({ navigation, defaultHandler }) => {
        // console.log(navigation, defaultHandler, 12)
        defaultHandler()
      }
    }
  }
}

const BottomTabNavigatorConfig = {
  initialRouteName: 'CHomePage',
  tabBarOptions: {
    activeTintColor: '#3C3C3C',
    inactiveTintColor: '#999999',
    labelStyle: {
      fontSize: 10,
      fontWeight: '400'
    },
    tabStyle: {
      paddingVertical: 5
    },
    style: {
      backgroundColor: '#F7F7F7',
      borderTopWidth: 0
    }
  },
  lazy: true,
  // backBehavior: 'none',
  keyboardHidesTabBar: true
}
const TabNavigator = createBottomTabNavigator(
  TabRouteConfigs,
  BottomTabNavigatorConfig
)
const TabbarContainer = createAppContainer(TabNavigator)
const mapActiontoProps = dispatch => ({
  doRequestUserInfoC (payload) {
    const promise = DO_REQUEST_USERINFO_C_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestMainPage (...payload) {
    const promise = DO_REQUEST_MAIN_PAGE_C_ACTION(...payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestMyCenterNumbers (payload) {
    const promise = DO_REQUEST_MY_CENTER_NUMBERS_ACTION(payload)
    dispatch(promise)
    return promise.payload
  }
})
const mapStatetoProps = ({ userinfo, CMineCenterStore, im }) => ({
  userinfo,
  CMineCenterStore,
  isRed: im.isRed
})

class MainTab extends React.Component {
  static router = TabbarContainer.router

  render () {
    const { screenProps, navigation, isRed } = this.props
    const bridge = !!isRed
    const { state: { index: activeIndex } } = navigation
    console.info('handleNavigationChange', navigation)
    return (
      <TabbarContainer
        screenProps={{ ...screenProps, bridge, activeIndex }}
        navigation={navigation}
      />
    )
  }

  componentDidMount () {
    console.log('CMainTab componentDidMount', this.props)
    this.jpushConfigInit()
    const {
      userinfo: { userId },
      doRequestUserInfoC,
      doRequestMainPage,
      doRequestMyCenterNumbers
    } = this.props
    if (userId) {
      doRequestUserInfoC({ params: { userId } }).finally(() => {
        console.log('componentDidMount,finally')
        const {
          userinfo: {
            C: { userId: userIdC }
          }
        } = this.props
        if (userIdC) {
          doRequestMainPage({ params: { userId } })
          doRequestMyCenterNumbers({ type: 'C', userId })
          IMController.initNIMc()
        } else {
          IMController.destroy().then(() => {
            IMController.initData()
          })
        }
      })
    }
    AppState.addEventListener('change', this.handleAppStateChange)
    initKeywordBlockObj()
  }

  componentDidUpdate (prevProps, prevState) {
    this.jpushConfigUpdate(
      prevProps.userinfo.userId,
      this.props.userinfo.userId
    )
    this.imConfigUpdate(
      prevProps.userinfo.C.userId,
      this.props.userinfo.C.userId
    )
  }

  /* jupush */
  jpushConfigInit = () => {
    // JPushModule.initPush()
    if (IS_IOS) {
      JPushModule.getRegistrationID(this.getRegistrationIDHandle)
      JPushModule.getLaunchAppNotification(this.getLaunchAppNotificationHandle)
      JPushModule.addReceiveNotificationListener(
        this.receiveNotificationListener
      )
      JPushModule.addReceiveOpenNotificationListener(
        this.openNotificationListener
      )
      JPushModule.addGetRegistrationIdListener(this.getRegistrationIdListener)
    } else {
      JPushModule.initPush()
      JPushModule.getInfo(map => {
        console.info('notifyJSDidLoad', map)
      })
      JPushModule.notifyJSDidLoad(resultCode => {
        if (resultCode === 0) {
          console.info('notifyJSDidLoad')
          JPushModule.addReceiveNotificationListener(
            this.receiveNotificationListener
          )
          JPushModule.addReceiveOpenNotificationListener(
            this.openNotificationListener
          )
          JPushModule.addGetRegistrationIdListener(
            this.getRegistrationIdListener
          )
        }
      })
    }
  }

  jpushConfigDeinit = () => {
    JPushModule.removeReceiveNotificationListener(
      this.receiveNotificationListener
    )
    JPushModule.removeReceiveOpenNotificationListener(
      this.openNotificationListener
    )
    JPushModule.removeGetRegistrationIdListener(this.getRegistrationIdListener)
    console.log('Will clear all notifications')
    JPushModule.clearAllNotifications()
  }

  jpushConfigUpdate = (prevUserId, userId) => {
    if (!prevUserId && userId) {
      console.log('CMainTab 重新登录', `c_${userId}`)
      JPushModule.setAlias(`c_${userId}`, result => {
        console.log('setAlias', result)
      })
    } else if (prevUserId && !userId) {
      console.log('CMainTab 退出登录')
      JPushModule.deleteAlias(() => {
        console.log('deleteAlias')
      })
    }
  }

  imConfigUpdate = (prevUserId, userId) => {
    if (!prevUserId && userId) {
      console.log('im 重新登录')
      IMController.initNIMc()
    } else if (prevUserId && !userId) {
      console.log('im 退出登录')
      IMController.destroy().then(() => {
        IMController.initData()
      })
    }
  }

  getRegistrationIDHandle = registrationId => {
    console.log('getRegistrationIDHandle, registrationId ' + registrationId)
    const {
      userinfo: { userId }
    } = this.props
    JPushModule.deleteAlias(() => {
      console.log('deleteAlias')
      if (registrationId && userId) {
        JPushModule.setAlias(`c_${userId}`, result => {
          console.log('setAlias', result)
        })
      }
    })
  }

  /* iOS Only 点击推送启动应用的时候原生会将该 notification 缓存起来，该方法用于获取缓存 notification */
  getLaunchAppNotificationHandle = map => {
    console.log('getLaunchAppNotificationHandle map: ' + map)
    this.openNotificationListener(map)
  }

  /* 监听：接收推送事件 */
  receiveNotificationListener = map => {
    console.log('receiveNotificationListener map: ' + JSON.stringify(map))
  }

  /* 监听：点击推送事件 */
  openNotificationListener = (map = {}) => {
    console.info('openNotificationListener map: ' + JSON.stringify(map))
    const { extras = {} } = map
    const extrasObj = isString(extras) ? JSON.parse(extras) : extras
    const { pushType } = extrasObj
    console.info('openNotificationListener pushType', pushType)
    switch (pushType) {
      case 'im':
        this.props.navigation.navigate('CMessagePage')
        break
      default:
        break
    }
  }

  handleAppStateChange = appState => {
    console.log('handleAppStateChange')
    if (appState === 'inactive') {
      JPushModule.clearAllNotifications()
    }
  }

  componentWillUnmount () {
    console.log('CMainTab componentWillUnmount')
    AppState.removeEventListener('change', this.handleAppStateChange)
    IMController.destroy().then(() => {
      IMController.initData()
    })
    this.jpushConfigDeinit()
  }
}

MainTab.propTypes = {
  userinfo: PropTypes.object,
  CMineCenterStore: PropTypes.object,
  navigation: PropTypes.object,
  isRed: PropTypes.bool
}
export default connect(
  mapStatetoProps,
  mapActiontoProps
)(MainTab)
